﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//Adding
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;
using System.Data.SqlClient;
using KPIS.GERP.GFMS.DAL;

namespace KPIS.GERP.GFMS.APP.App_UI
{
    public partial class ViewInvoiceReport : System.Web.UI.Page
    {

        #region Fields

        private string _receiveDate;
        private string _receiveSeq;
        private string _receiveMode;
       

        ReportDocument cryRpt = new ReportDocument();
        D_FIM_Receives dal = new D_FIM_Receives();

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            _receiveDate = Request["receivedate"];
            _receiveSeq = Request["receiveseq"];
            _receiveMode = Request["receivemode"];

            if (_receiveDate != null && _receiveMode != null)
            {
                string[] arr = _receiveDate.Split('/');
                string receiveDateEng = string.Format("{0}-{1}-{2}", (int.Parse(arr[2]) < 2500 ? arr[2] : (int.Parse(arr[2])).ToString()), arr[1], arr[0]);
                string receiveDateTH = string.Format("{0}-{1}-{2}", (int.Parse(arr[2]) < 2500 ? arr[2] : (int.Parse(arr[2]) - 543).ToString()), arr[1], arr[0]);

                loadReportView(receiveDateEng, _receiveMode, receiveDateTH);
            }
            else
            {
                loadReportView();
            }

            //PrinterList();
        }

        protected void btn_printInv_Click(object sender, EventArgs e)
        {
            ReportDocument repDoc = cryRpt;

            Response.Buffer = false;
            Response.ClearContent();
            Response.ClearHeaders();

            try
            {
                repDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Customers");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                ex = null;
            }
        }

        #endregion

        #region Private Methods

        private void PrinterList()
        {
            // POPULATE THE COMBO BOX.
            if (System.Drawing.Printing.PrinterSettings.InstalledPrinters != null)
            {
                foreach (string sPrinters in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                {
                    cboPrinterList.Items.Add(sPrinters);
                }
            }
        }

        private DataTable PrintHAInvoice(int ReceiveSeq)
        {
            string strSQL = string.Empty;
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            DataSet ds = new DataSet();

            if(chkDetailItem(ReceiveSeq) == 0)
            {
                strSQL = string.Format("SELECT receive_seq,temp_contact,contact_branch,contact_address,r.receive_date,r.remarks,exclude_vat,vat_amount,amount,cheque_no,np.prefix_name+emp.first_name+' '+emp.last_name as fullemp_name,pos_name,branch_name,bank_name,qty,discount_percent,discount,unit_price,ROW_NUMBER()OVER(ORDER BY r.receive_seq) as item_seq"
                    + " FROM IcmMasContact c"
                    + " FULL OUTER JOIN fim_receives r ON r.contact_seq = c. ConId"
                    + " FULL OUTER JOIN hrm_ps_employees emp ON r.created_by = emp.emp_seq"
                    + " FULL OUTER JOIN mas_name_prefixes np on emp.name_prefix_seq = np.name_prefix_seq"
                    + " FULL OUTER JOIN fim_money_requests mr ON r.money_req_seq = mr.money_req_seq"
                    + " FULL OUTER JOIN fim_petitions pt ON r.petition_seq = pt.petition_seq"
                    + " FULL OUTER JOIN fim_mas_receive_types rt ON r.receive_type_seq = rt.receive_type_seq"
                    + " FULL OUTER JOIN hrm_mp_positions pos ON emp.pos_seq = pos.pos_seq"
                    + " FULL OUTER JOIN fim_mas_bank_branchs bkb ON r.branch_seq = bkb.branch_seq"
                    + " FULL OUTER JOIN fim_mas_banks bk ON bkb.bank_seq = bk.bank_seq"
                    + " WHERE r.receive_seq = {0} AND r.record_status not like '{1}'",ReceiveSeq,"D");
            }
            else
            {
                strSQL = string.Format("SELECT r.receive_seq,temp_contact,contact_branch,contact_address,r.receive_date,exclude_vat,vat_amount,r.amount,cheque_no,np.prefix_name+emp.first_name+' '+emp.last_name as fullemp_name,pos_name,branch_name,bank_name,rdtl.qty,discount_percent,discount,rdtl.unit_price,receive_dtls_name as remarks,ROW_NUMBER()OVER(ORDER BY r.receive_seq) as item_seq, rdtl.amount as dtl_amount"
                    + " FROM IcmMasContact c"
                    + " FULL OUTER JOIN fim_receives r ON r.contact_seq = c. ConId"
                    + " FULL OUTER JOIN hrm_ps_employees emp ON r.created_by = emp.emp_seq"
                    + " FULL OUTER JOIN mas_name_prefixes np on emp.name_prefix_seq = np.name_prefix_seq"
                    + " FULL OUTER JOIN fim_money_requests mr ON r.money_req_seq = mr.money_req_seq"
                    + " FULL OUTER JOIN fim_petitions pt ON r.petition_seq = pt.petition_seq"
                    + " FULL OUTER JOIN fim_mas_receive_types rt ON r.receive_type_seq = rt.receive_type_seq"
                    + " FULL OUTER JOIN hrm_mp_positions pos ON emp.pos_seq = pos.pos_seq"
                    + " FULL OUTER JOIN fim_mas_bank_branchs bkb ON r.branch_seq = bkb.branch_seq"
                    + " FULL OUTER JOIN fim_mas_banks bk ON bkb.bank_seq = bk.bank_seq"
                    + " FULL OUTER JOIN fim_receive_dtls rdtl ON r.receive_seq = rdtl.receive_seq"
                    + " WHERE r.receive_seq = {0} AND r.record_status not like '{1}'", ReceiveSeq, "D");
            }

            using (SqlConnection conn = new SqlConnection(strConn))
            {
                using(SqlDataAdapter adp = new SqlDataAdapter(strSQL,conn))
                {
                    adp.Fill(ds,"Invoice");
                }
            }

            return ds.Tables["Invoice"];
        }

        private DataTable PrintHAInvoice(string createWhen, string receivemode)
        {
            string strSQL;
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            DataSet ds = new DataSet();

            strSQL = string.Format("SELECT receive_seq,temp_contact,contact_branch,contact_address,r.receive_date,r.remarks,exclude_vat,vat_amount,amount,cheque_no,np.prefix_name+emp.first_name+' '+emp.last_name as fullemp_name,pos_name,branch_name,bank_name,qty,discount_percent,discount,unit_price"
                    + " FROM IcmMasContact c"
                    + " FULL OUTER JOIN fim_receives r ON r.contact_seq = c. ConId"
                    + " FULL OUTER JOIN hrm_ps_employees emp ON r.created_by = emp.emp_seq"
                    + " FULL OUTER JOIN mas_name_prefixes np on emp.name_prefix_seq = np.name_prefix_seq"
                    + " FULL OUTER JOIN fim_money_requests mr ON r.money_req_seq = mr.money_req_seq"
                    + " FULL OUTER JOIN fim_petitions pt ON r.petition_seq = pt.petition_seq"
                    + " FULL OUTER JOIN fim_mas_receive_types rt ON r.receive_type_seq = rt.receive_type_seq"
                    + " FULL OUTER JOIN hrm_mp_positions pos ON emp.pos_seq = pos.pos_seq"
                    + " FULL OUTER JOIN fim_mas_bank_branchs bkb ON r.branch_seq = bkb.branch_seq"
                    + " FULL OUTER JOIN fim_mas_banks bk ON bkb.bank_seq = bk.bank_seq"
                    + " WHERE r.receive_date like '{0}%' AND r.record_status not like '{1}' AND r.receive_mode = {2} AND r.source like '{3}'", createWhen, "D", receivemode, "PrepareRec");

            using (SqlConnection conn = new SqlConnection(strConn))
            {
                using (SqlDataAdapter adp = new SqlDataAdapter(strSQL, conn))
                {
                    adp.Fill(ds, "Invoice");
                }
            }

            return ds.Tables["Invoice"];
        }

        private int chkDetailItem(int ReceiveSeq)
        {
            int dtlCount = 0;

            string strSQL;
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            DataSet ds = new DataSet();

            strSQL = string.Format("SELECT *"
                    + " FROM fim_receive_dtls"
                    + " WHERE receive_seq = {0} AND record_status not like '{1}'", ReceiveSeq, "D");

            using (SqlConnection conn = new SqlConnection(strConn))
            {
                using (SqlDataAdapter adp = new SqlDataAdapter(strSQL, conn))
                {
                    adp.Fill(ds, "Invoice");
                }
            }

            dtlCount = ds.Tables[0].Rows.Count;

            return dtlCount;
        }

        #endregion

        #region Public Methods

        //เปลี่ยนวิธี เพราะเวลาเรียกรายงานหลายตัวช้าจนหลุด
        //public void loadReportView(string receiveDate)
        //{
        //    cryRpt.Load(Server.MapPath("~//Reports//HAInvoice.rpt"));
        //    cryRpt.SetDatabaseLogon("sa", "root123456789");

        //    /* โค้ดไม่ให้ถาม Login Dialog ใช้แล้วโหลดช้ามาก */
        //    CrystalDecisions.Shared.TableLogOnInfo crTableLogonInfo;
        //    CrystalDecisions.Shared.ConnectionInfo cnConnInfo = new ConnectionInfo();

        //    cnConnInfo.ServerName = "localhost";
        //    cnConnInfo.DatabaseName = "GERP";
        //    cnConnInfo.UserID = "sa";
        //    cnConnInfo.Password = "root123456789";

        //    foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in cryRpt.Database.Tables)
        //    {
        //        crTableLogonInfo = crTable.LogOnInfo;
        //        crTableLogonInfo.ConnectionInfo = cnConnInfo;
        //        crTable.ApplyLogOnInfo(crTableLogonInfo);
        //    }


        //    ParameterFieldDefinitions crParameterFieldDefinitions;
        //    ParameterFieldDefinition crParameterFieldDefinition;
        //    ParameterValues crParameterValues = new ParameterValues();
        //    ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

        //    crParameterDiscreteValue.Value = receiveDate;
        //    crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
        //    crParameterFieldDefinition = crParameterFieldDefinitions["receivedate"];
        //    crParameterValues = crParameterFieldDefinition.CurrentValues;

        //    crParameterValues.Clear();
        //    crParameterValues.Add(crParameterDiscreteValue);
        //    crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

        //    CrystalReportViewer1.ReportSource = cryRpt;
        //    CrystalReportViewer1.DataBind();
        //}

        public void loadReportView()
        {
            string path = string.Empty;

            if (chkDetailItem(int.Parse(_receiveSeq)) == 0)
            {
                path = "~//Reports//HAInvoice2.rpt";
            }
            else
            {
                path = "~//Reports//HAInvoice3.rpt";
            }

            cryRpt.Load(Server.MapPath(path));
            //ย้ายฟังก์ชั่นมาไว้ในฟอร์มชั่วคราว
            //cryRpt.SetDataSource(dal.PrintHAInvoice(int.Parse(_receiveSeq)));
            var data = PrintHAInvoice(int.Parse(_receiveSeq));
            cryRpt.SetDataSource(data);
            DateTime date = Convert.ToDateTime(data.Rows[0]["receive_date"]);
            string dateString = date.ToLongDateString();
            cryRpt.SetParameterValue(0, dateString);
            //เอ็กซ์พอร์ทไฟล์ออกมาเลย
            cryRpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Customers");
            
            //ไม่แสดงรายงานในคริสตัลวิว
            //CrystalReportViewer1.ReportSource = cryRpt;
            //CrystalReportViewer1.DataBind();

            //CrystalReportViewer1.HasPrintButton = false;
            //CrystalReportViewer1.HasExportButton = false;
            //CrystalReportViewer1.PrintMode = CrystalDecisions.Web.PrintMode.ActiveX;
        }

        public void loadReportView(string createWhen,string receivemode, string date)
        {
            cryRpt.Load(Server.MapPath("~//Reports//HAInvoice2.rpt"));
            cryRpt.SetDataSource(PrintHAInvoice(date, receivemode));
            cryRpt.SetParameterValue(0, Convert.ToDateTime(createWhen).ToLongDateString());
            cryRpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Customers");

            //CrystalReportViewer1.ReportSource = cryRpt;
            //CrystalReportViewer1.DataBind();

            //CrystalReportViewer1.HasPrintButton = false;
            //CrystalReportViewer1.HasExportButton = false;
            //CrystalReportViewer1.PrintMode = CrystalDecisions.Web.PrintMode.ActiveX;
        }

        #endregion                
    }
}